package org.example.struct.array;

/**
 * @author liyishan
 * @date 2024/2/18 09:28
 * @apiNote
 */

public class M0103ReplaceSpaces {
    public static void main(String[] args) {
        String s = "Mr John Smith    ";
        System.out.println(replaceSpaces1(s, 13));
    }

    public String replaceSpaces(String S, int length) {
        return S.substring(0, length).replace(" ", "%20");
    }

    public static String replaceSpaces1(String S, int length) {
        String[] chars = new String[length];
        for (int i = 0; i < length; i++) {
            if (S.charAt(i) != ' ') {
                chars[i] = String.valueOf(S.charAt(i));
            } else {
                chars[i] = "%20";
            }
        }
        return String.join("", chars);
    }

    public String replaceSpaces2(String S, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            char ch = S.charAt(i);
            if (ch == ' ') {
                sb.append("%20");
                continue;
            }
            sb.append(ch);
        }
        return sb.toString();
    }

    public String replaceSpaces3(String S, int length) {
        char[] ch = new char[length * 3];
        int index = 0;
        for (int i = 0; i < length; i++) {
            char c = S.charAt(i);
            if (c == ' ') {
                ch[index++] = '%';
                ch[index++] = '2';
                ch[index++] = '0';
            } else {
                ch[index] = c;
                index++;
            }
        }
        return new String(ch, 0, index);
    }
}
